package com.kfm.pm;

import java.io.IOException;
import java.sql.*;

public class DBUtils {

    private final String JDBC_URL = "jdbc:mysql://localhost:3306/manager";
    private final String USERNAME = "root";
    private final String PASSWORD = "";

    // 一个对象只有一个 Connection 对象
    private Connection connection;

    // 执行 查询语句
    public ResultSet executeQuery(String sql, Object... objects) throws SQLException, ClassNotFoundException {
        Connection connection = getConnection();
        PreparedStatement prepared = connection.prepareStatement(sql);
        setObject(prepared, objects);
        return prepared.executeQuery();
    }
    // 执行查询语句之外的语句
    public int executeUpdate(String sql, Object... objects) throws SQLException, ClassNotFoundException {
        Connection connection = getConnection();
        PreparedStatement prepared = connection.prepareStatement(sql);
        setObject(prepared, objects);
        return prepared.executeUpdate();
    }

    private void setObject(PreparedStatement preparedStatement, Object... objects) throws SQLException {
        for (int i = 0; i < objects.length; i++) {
            preparedStatement.setObject(i + 1, objects[i]);
        } // 将占位符替换成对应的参数
    }


    private Connection getConnection() throws ClassNotFoundException, SQLException {
        if (connection == null) {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
        }
        return connection;
    }

    public void close() throws SQLException {
        if (connection != null) {
            connection.close();
            connection = null;
        }
    }
}

class Test02 {

    public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
        DBUtils dbUtils = new DBUtils();
        dbUtils.executeQuery("select * from users");
        dbUtils.close();
    }
}
